package com.longrise.android.byjk.plugins.course.coursedetail.learningagreement;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;

import com.longrise.android.byjk.R;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.education.insurance.InsuranceActivity;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoConsts;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoParams;
import com.longrise.android.byjk.utils.GetWebUrlHelper;
import com.longrise.common.base.web.BaseWebActivity;
import com.longrise.common.base.web.BaseWebBridge;
import com.longrise.common.base.web.BaseWebClient;
import com.longrise.common.datasource.local.sp.CacheUtils;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by callxkj on 2018/1/16.
 * 学习协议
 */

public class LearningAgreementActivity extends BaseWebActivity {

    private WebView mWv;
    private VideoParams mVideoParams;
    private Button mBt;

    /**
     * 检查是否需要显示当前的学习协议
     */
    public static void toCheckAndShow(Activity activity, VideoParams videoParams) {
        if (isReaded(videoParams.mCourseId)) { //如果已经阅读过学习协议 那么直接跳转到课程详情页面
            Intent intent = new Intent(activity, InsuranceActivity.class);
            intent.putExtra(VideoConsts.VIDEO_PARAMS_PARCELABLE, videoParams);
            activity.startActivity(intent);
        } else { //如果没有阅读过学习协议 那么跳转到协议页面
            Intent intent = new Intent(activity, LearningAgreementActivity.class);
            intent.putExtra(VideoConsts.VIDEO_PARAMS_PARCELABLE, videoParams);
            activity.startActivity(intent);
            activity.overridePendingTransition(R.anim.activity_up_down_open, R.anim.activity_anim_stay);
        }
    }

    /**
     * 获取是否已经阅读学习协议的状态
     */
    private static boolean isReaded(String courseid) {
        return CacheUtils.getBoolean("LearningAgreement" + UserInfor.getInstance().getUsersfzh() + courseid, false);
    }

    /**
     * 设置已经阅读过学习协议
     */
    private static void setReaded(String courseid) {
        CacheUtils.setBoolean("LearningAgreement" + UserInfor.getInstance().getUsersfzh() + courseid, true);
    }


    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_learningagreement;
    }

    @Override
    public WebView getWebView() {
        return mWv;
    }

    @Override
    public void init() {
        mWv = (WebView) findViewById(R.id.learningagreement_wv);
        mBt = (Button) findViewById(R.id.learningagreement_confirm_bt);

        Toolbar toolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        toolbar.setNavigationIcon(R.drawable.umeng_by_ic_close_black);
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        mVideoParams = extras.getParcelable(VideoConsts.VIDEO_PARAMS_PARCELABLE);
        initEvent();
    }

    @Override
    public void initData() {
        GetWebUrlHelper.getWebUrl(GetWebUrlHelper.XXXY, new GetWebUrlHelper.OnGetWebUrlResultListener() {
            @Override
            public void onSuccess(String url) {
                loadUrl(url);
            }

            @Override
            public void onError(String errormsg) {
                showToast(errormsg);
            }
        });
    }

    @Override
    public BaseWebBridge getwebBridge() {
        return null;
    }

    @Override
    public BaseWebClient getWebClient() {
        return new LearningAgreementClient(this);
    }


    private void initEvent() {
        mBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LearningAgreementActivity.this, InsuranceActivity.class);
                intent.putExtra(VideoConsts.VIDEO_PARAMS_PARCELABLE, mVideoParams);
                startActivity(intent);
                setReaded(mVideoParams.mCourseId);
                finish();
            }
        });

        //按钮倒计时
        Disposable disposable = Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        long result = 5;
                        result = result - aLong;
                        if (result >= 0) {
                            return result;
                        } else {
                            return (long) 0;
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (aLong <= 0) {
                            mBt.setText("我已阅读并同意");
                            mBt.setEnabled(true);
                            mBt.setTextColor(Color.parseColor("#FFFFFF"));
                        } else {
                            mBt.setText("我已阅读并同意（" + aLong + "s）");
                            mBt.setEnabled(false);
                            mBt.setTextColor(Color.parseColor("#666666"));
                        }
                    }
                });

        mRxmanager.addDisposable(disposable);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.activity_anim_stay, R.anim.activity_up_down_close);
    }
}
